<template>
    <div id="map" class="mapC"></div>
</template>

<script>
import 'ol/ol.css'
import Feature from 'ol/Feature'
import LineString from 'ol/geom/LineString'
import Map from 'ol/Map'
// import Stamen from 'ol/source/Stamen'
import VectorSource from 'ol/source/Vector'
import View from 'ol/View'
import {Stroke, Style} from 'ol/style'
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer'
import {XYZ} from 'ol/source'
import {getVectorContext} from 'ol/render'
export default {
  name: 'index',
  data () {
    return {
      map: null,
      style: null,
      flightsSource: null,
      flightsLayer: null,
      pointsPerMs: 0.1,
      raset: null,
      raset1: null
    }
  },
  mounted () {
    this.initMap()
    this.getData()
  },
  methods: {
    initMap () {
      this.style = new Style({
        stroke: new Stroke({
          color: '#EAE911',
          width: 2
        })
      })
      this.raset = new TileLayer({
        name: 'map1',
        title: 'map1',
        source: new XYZ({
          url: '/mapServe/tdt/map/{z}/{x}/{y}.png'
        }),
        visible: true
      })
      this.raset1 = new TileLayer({
        name: 'map2',
        title: 'map2',
        source: new XYZ({
          url: '/mapServe/tdt/mapi/{z}/{x}/{y}.png'
        }),
        visible: true
      })
      this.map = new Map({
        target: 'map',
        layers: [this.raset, this.raset1],
        view: new View({
          center: [0, 0],
          zoom: 4
          // projection: 'EPSG:4326'
        })
      })
    },
    getData () {
      let that = this
      that.flightsSource = new VectorSource({
        wrapX: false,
        attributions:
        'Flight data by ' +
        '<a href="https://openflights.org/data.html">OpenFlights</a>,',
        loader: function () {
          const url = 'zlocal/data/openflights/flights.json'
          fetch(url)
            .then(function (response) {
              return response.json()
            })
            .then(function (json) {
              const flightsData = json.flights
              for (let i = 0; i < flightsData.length; i++) {
                const flight = flightsData[i]
                const from = flight[0]
                const to = flight[1]

                // create an arc circle between the two locations
                const arcGenerator = new window.arc.GreatCircle(
                  {x: from[1], y: from[0]},
                  {x: to[1], y: to[0]}
                )

                const arcLine = arcGenerator.Arc(100, {offset: 10})
                if (arcLine.geometries.length === 1) {
                  const line = new LineString(arcLine.geometries[0].coords)
                  line.transform('EPSG:4326', 'EPSG:3857')

                  const feature = new Feature({
                    geometry: line,
                    finished: false
                  })
                  // add the feature with a delay so that the animation
                  // for all features does not start at the same time
                  that.addLater(feature, i * 50)
                }
              }
              that.raset.on('postrender', that.animateFlights)
            })
        }
      })
      that.flightsLayer = new VectorLayer({
        source: that.flightsSource,
        style: function (feature) {
          // if the animation is still active for a feature, do not
          // render the feature with the layer style
          if (feature.get('finished')) {
            return that.style
          } else {
            return null
          }
        }
      })
      that.map.addLayer(that.flightsLayer)
    },
    addLater (feature, timeout) {
      window.setTimeout(() => {
        feature.set('start', new Date().getTime())
        this.flightsSource.addFeature(feature)
      }, timeout)
    },
    animateFlights (event) {
      const vectorContext = getVectorContext(event)
      const frameState = event.frameState
      vectorContext.setStyle(this.style)

      const features = this.flightsSource.getFeatures()
      for (let i = 0; i < features.length; i++) {
        const feature = features[i]
        if (!feature.get('finished')) {
          // only draw the lines for which the animation has not finished yet
          const coords = feature.getGeometry().getCoordinates()
          const elapsedTime = frameState.time - feature.get('start')
          const elapsedPoints = elapsedTime * this.pointsPerMs

          if (elapsedPoints >= coords.length) {
            feature.set('finished', true)
          }

          const maxIndex = Math.min(elapsedPoints, coords.length)
          const currentLine = new LineString(coords.slice(0, maxIndex))

          // directly draw the line with the vector context
          vectorContext.drawGeometry(currentLine)
        }
      }
      // tell OpenLayers to continue the animation
      this.map.render()
    }
  }
}
</script>

<style scoped>

</style>
